<template>
  <view>
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title"></view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
        <button class="uni-button" type="default" size="mini" @click="search">搜索</button>
        <button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
        <button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length" @click="delTable">批量删除</button>
        <download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
          <button class="uni-button" type="primary" size="mini">导出 Excel</button>
        </download-excel>
      </view>
    </view>
    <view class="uni-container">
      <unicloud-db ref="udb" :collection="collectionList" page-data="replace"
        :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
        v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual" @load="onqueryload">
        <uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
          <uni-tr>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'merchant_code')" sortable @sort-change="sortChange($event, 'merchant_code')">商户编号</uni-th>
            <uni-th align="center" width="260" filter-type="search" @filter-change="filterChange($event, 'store_name')" sortable @sort-change="sortChange($event, 'store_name')">店铺名称</uni-th>
            <uni-th align="center" width="120" sortable @sort-change="sortChange($event, 'business_licence_id')">营业执照</uni-th>
            <uni-th align="center" width="120" sortable @sort-change="sortChange($event, 'other_licence_id')">经营许可证</uni-th>
            <uni-th align="center" width="120" sortable @sort-change="sortChange($event, 'store_icon')">店铺图标</uni-th>
            <uni-th align="center" width="120" sortable @sort-change="sortChange($event, 'store_plaque_icon')">店铺牌匾</uni-th>
            <uni-th align="center" width="120" sortable @sort-change="sortChange($event, 'store_cover_icon')">店铺封面</uni-th>
            <uni-th align="center" width="130" filter-type="search" @filter-change="filterChange($event, 'store_phone')" sortable @sort-change="sortChange($event, 'store_phone')">店铺电话</uni-th>
            <uni-th align="center" width="300" sortable @sort-change="sortChange($event, 'store_category_menuId')">店铺类型</uni-th>
            <uni-th align="center" width="255" filter-type="select" :filter-data="options.filterData.store_work_date_localdata" @filter-change="filterChange($event, 'store_work_date')">营业日期</uni-th>
            <uni-th align="center" width="130" sortable @sort-change="sortChange($event, 'store_work_time')">营业时段</uni-th>
            <uni-th align="center" width="130" sortable @sort-change="sortChange($event, 'store_delivery_time')">配送时段</uni-th>
            <uni-th align="center" width="110" filter-type="select" :filter-data="options.filterData.store_food_finish_time_localdata" @filter-change="filterChange($event, 'store_food_finish_time')">出餐时间</uni-th>
            <uni-th align="center" width="110" filter-type="select" :filter-data="options.filterData.store_food_pack_fee_localdata" @filter-change="filterChange($event, 'store_food_pack_fee')">餐具费用</uni-th>
            <uni-th align="center" width="110"  filter-type="select" :filter-data="options.filterData.store_food_delivery_fee_localdata" @filter-change="filterChange($event, 'store_food_delivery_fee')">基础配送费</uni-th>
            <uni-th align="center" width="110" filter-type="range" @filter-change="filterChange($event, 'store_start_delivery_money')" sortable @sort-change="sortChange($event, 'store_start_delivery_money')">起送金额</uni-th>
            <uni-th align="center" width="110" filter-type="range" @filter-change="filterChange($event, 'commission_percentage')" sortable @sort-change="sortChange($event, 'commission_percentage')">店铺抽佣</uni-th>
            <uni-th align="center" width="150" sortable @sort-change="sortChange($event, 'store_address_xy')">地图经纬坐标</uni-th>
            <uni-th align="center" width="230" filter-type="search" @filter-change="filterChange($event, 'store_address_info')" sortable @sort-change="sortChange($event, 'store_address_info')">店铺地址</uni-th>
            <uni-th align="center" width="400" filter-type="search" @filter-change="filterChange($event, 'store_notice')" sortable @sort-change="sortChange($event, 'store_notice')">店铺公告</uni-th>
            <uni-th align="center" width="110" filter-type="select" :filter-data="options.filterData.work_status_localdata" @filter-change="filterChange($event, 'work_status')">营业或休息</uni-th>
            <uni-th align="center" width="110" filter-type="select" :filter-data="options.filterData.enable_status_localdata" @filter-change="filterChange($event, 'enable_status')">店铺状态</uni-th>
            <uni-th align="center" width="250">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item,index) in data" :key="index">
            <uni-td align="center">{{item.merchant_code}}</uni-td>
            <uni-td align="center">

              <lay-tooltip v-if="item.store_name.length>12" :content="item.store_name" :isDark="false">
                <div class="flexStyle">
                  {{item.store_name.substr(0,12)+' ...'}}
                </div>
              </lay-tooltip>
            <div v-else>{{item.store_name}}</div>

            </uni-td>
            <uni-td align="center">
              <div v-if="item.business_licence_id.length>0">
                <div v-for="(it, i) in item.business_licence_id" :key="i">
                  <template v-for="(file,j) in it.company_license_icon">
                    <uni-file-picker :key="j" class="flexStyle" v-if="file.fileType == 'image'" :modelValue="file" :value="file" :file-mediatype="file.fileType" :imageStyles="imageStyles" readonly></uni-file-picker>
                    <uni-link v-else :href="file.url" :text="file.url" :key="j+1"></uni-link>
                  </template>
                </div>
              </div>
              <div class="flexStyle addFillData" v-else @click="navigateTo(`/uni_modules/compay-business-licence/pages/compay-business-licence/add`)">
                  <uni-icons type="compose" size="20" color="#0073f0" class="composeIcon"></uni-icons>
                  <div>点击上传</div>
              </div>
            </uni-td>

            <uni-td align="center">
              <div v-if="item.other_licence_id.length>0">
                <div v-for="(it, i) in item.other_licence_id" :key="i">
                  <template v-for="(file,index) in it.company_license_icon">
                    <uni-file-picker :key="index" class="flexStyle" v-if="file.fileType == 'image'" :modelValue="file" :value="file" :file-mediatype="file.fileType" :imageStyles="imageStyles" readonly></uni-file-picker>
                    <uni-link v-else :href="file.url" :text="file.url" :key="index+1"></uni-link>
                  </template>
                </div>
              </div>
              <div class="flexStyle addFillData" v-else @click="navigateTo(`/uni_modules/company-other-license/pages/company-other-license/add`)">
                  <uni-icons type="compose" size="20" color="#0073f0" class="composeIcon"></uni-icons>
                  <div>点击上传</div>
              </div>
            </uni-td>
            <uni-td align="center">
              <template v-for="(file, j) in item.store_icon">
                <uni-file-picker :key="j" class="flexStyle" v-if="file.fileType == 'image'" :modelValue="file" :value="file" :file-mediatype="file.fileType" :imageStyles="imageStyles" readonly></uni-file-picker>
                <uni-link v-else :href="file.url" :text="file.url" :key="j+1"></uni-link>
              </template>
            </uni-td>
            <uni-td align="center">
              <template v-for="(file, j) in item.store_plaque_icon">
                <uni-file-picker :key="j" class="flexStyle" v-if="file.fileType == 'image'" :modelValue="file" :value="file" :file-mediatype="file.fileType" :imageStyles="imageStyles" readonly></uni-file-picker>
                <uni-link v-else :href="file.url" :text="file.url" :key="j+1"></uni-link>
              </template>
            </uni-td>
            <uni-td align="center">
              <template v-for="(file, j) in item.store_cover_icon">
                <uni-file-picker :key="j" class="flexStyle" v-if="file.fileType == 'image'" :modelValue="file" :value="file" :file-mediatype="file.fileType" :imageStyles="imageStyles" readonly></uni-file-picker>
                <uni-link v-else :href="file.url" :text="file.url" :key="j+1"></uni-link>
              </template>
            </uni-td>
            <uni-td align="center">{{item.store_phone}}</uni-td>
            <uni-td align="center">
              <uni-data-picker :localdata="options.store_category_menuId_valuetotext" :value="item.store_category_menuId" :border="false" :readonly="true" split=","></uni-data-picker>
            </uni-td>
            <uni-td align="center">
              <uni-data-picker :localdata="options.store_work_date_valuetotext" :value="item.store_work_date" :border="false" :readonly="true" split=","></uni-data-picker>
            </uni-td>
            <uni-td align="center">
              <div class="flexColumnCenter">
                <div v-for="(it,i) in item.store_work_time" :key="i">
                  {{it.startH}}:{{it.startM}} - {{it.endH}}:{{it.endM}}
                </div>
              </div>
            </uni-td>
            <uni-td align="center">
              <div class="flexColumnCenter">
                <div v-for="(it,i) in item.store_delivery_time" :key="i">
                  {{it.startH}}:{{it.startM}} - {{it.endH}}:{{it.endM}}
                </div>
              </div>
            </uni-td>
            <uni-td align="center">{{options.store_food_finish_time_valuetotext[item.store_food_finish_time]}}</uni-td>
            <uni-td align="center">{{options.store_food_pack_fee_valuetotext[item.store_food_pack_fee]}}</uni-td>
            <uni-td align="center">{{options.store_food_delivery_fee_valuetotext[item.store_food_delivery_fee]}}</uni-td>
            <uni-td align="center">{{item.store_start_delivery_money/100}}元</uni-td>
            <uni-td align="center">{{item.commission_percentage/1000}}%</uni-td>
            <uni-td align="center">
              <div class="flexStyle" v-if="item.store_address_xy" style="font-size: 13px;">
                  经:{{ item.store_address_xy[0] }} 纬:{{ item.store_address_xy[1] }}
              </div>
            </uni-td>
            <uni-td align="center">
              <div class="flexStyle">
                <lay-tooltip :content="item.store_address_info" :isDark="false">
                <div class="flexStyle">
                  {{ item.city_id_array.map(it=>it.text).join('') }}
                </div>
              </lay-tooltip>
              </div>
            </uni-td>
            <uni-td align="center">
              <lay-tooltip v-if="item.store_notice.length>20" :content="item.store_notice" :isDark="false">
                <div class="flexStyle">
                  {{item.store_notice.substr(0,20)+' ...'}}
                </div>
              </lay-tooltip>
            <div v-else>{{item.store_notice}}</div>
            </uni-td>
            <uni-td align="center">
              {{ options.work_status_valuetotext[item.work_status] }}
            </uni-td>
            <uni-td align="center">
              {{ options.enable_status_valuetotext[item.enable_status] }}
            </uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <lay-button type="primary" size="sm" @click="layerMerchantWallet(item)">钱包</lay-button>
                <lay-button type="normal" @click="navigateTo('./edit?id='+item._id, false)" size="sm">修改</lay-button>
                <lay-button type="danger" @click="confirmDelete(item._id)" size="sm">删除</lay-button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<style lang="stylus" scoped>
.addFillData
  cursor pointer
  color: #0073f0
  user-select: none
  &:hover
    color:#0857ad
    .composeIcon
      color:#0857ad !important
</style>

<script>
import { layerMerchantWallet } from '@/common/layer-com.js'
import UQRCode from 'uqrcodejs';
  import { enumConverter, filterToWhere } from '../../js_sdk/validator/food-merchant-list.js';

  const db = uniCloud.database()
  // 表查询配置
  const dbOrderBy = '' // 排序字段
  const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
  // 分页配置
  const pageSize = 20
  const pageCurrent = 1

  const orderByMapping = {
    "ascending": "asc",
    "descending": "desc"
  }

const mainTableField="merchant_money_amount,commission_percentage,store_category_menuId,store_cover_icon,city_id_array,store_address_xy,work_status,enable_status,business_licence_id,other_licence_id,merchant_code,store_name,store_icon,store_plaque_icon,store_phone,store_work_date,store_work_time,store_delivery_time,store_food_finish_time,store_food_pack_fee,store_food_delivery_fee,store_start_delivery_money,store_address_info,store_notice,google_secret,google_otpauth_url"
  export default {
    data() {
      return {
        collectionList: [
          db.collection('food-merchant-list').where(this.where).field(mainTableField).getTemp(),
          db.collection('compay-business-licence').field(`merchant_id,company_license_icon`).getTemp(),
          db.collection('company-other-license').field(`merchant_id,company_license_icon,company_license_type`).getTemp()
        ],
        query: '',
        where: '',
        orderby: dbOrderBy,
        orderByFieldName: "",
        selectedIndexs: [],
        options: {
          pageSize,
          pageCurrent,
          filterData: {
            'work_status_localdata':[
                {
                  "text":"营业",
                  "value":0
                },
                {
                  "text":"休息",
                  "value":1
                }
            ],
            'enable_status_localdata':[
                {
                  "text":"审核通过",
                  "value":0
                },
                {
                  "text":"审核失败",
                  "value":1
                },
                {
                  "text":"正在审核",
                  "value":2
                },
                {
                  "text":"异常店铺",
                  "value":3
                }
            ],

            "store_work_date_localdata": [
              {
                "text": "周一",
                "value": 0
              },
              {
                "text": "周二",
                "value": 1
              },
              {
                "text": "周三",
                "value": 2
              },
              {
                "text": "周四",
                "value": 3
              },
              {
                "text": "周五",
                "value": 4
              },
              {
                "text": "周六",
                "value": 5
              },
              {
                "text": "周日",
                "value": 6
              }
            ],
            "store_food_finish_time_localdata": [
              {
                "text": "20分钟内",
                "value": 1200000
              },
              {
                "text": "30分钟内",
                "value": 1800000
              },
              {
                "text": "40分钟内",
                "value": 2400000
              },
              {
                "text": "50分钟内",
                "value": 3000000
              },
              {
                "text": "60分钟内",
                "value": 3600000
              }
            ],
            "store_food_pack_fee_localdata": [
              {
                "text": "0元",
                "value": 0
              },
              {
                "text": "1元",
                "value": 100
              },
              {
                "text": "2元",
                "value": 200
              },
              {
                "text": "3元",
                "value": 300
              },
              {
                "text": "4元",
                "value": 400
              },
              {
                "text": "5元",
                "value": 500
              },
              {
                "text": "6元",
                "value": 600
              },
              {
                "text": "7元",
                "value": 700
              },
              {
                "text": "8元",
                "value": 800
              },
              {
                "text": "9元",
                "value": 900
              },
              {
                "text": "10元",
                "value": 1000
              }
            ],
            "store_food_delivery_fee_localdata": [
              {
                "text": "0元",
                "value": 0
              },
              {
                "text": "1元",
                "value": 100
              },
              {
                "text": "2元",
                "value": 200
              },
              {
                "text": "3元",
                "value": 300
              },
              {
                "text": "4元",
                "value": 400
              },
              {
                "text": "5元",
                "value": 500
              },
              {
                "text": "6元",
                "value": 600
              },
              {
                "text": "7元",
                "value": 700
              },
              {
                "text": "8元",
                "value": 800
              },
              {
                "text": "9元",
                "value": 900
              },
              {
                "text": "10元",
                "value": 1000
              }
            ]
          },
          ...enumConverter
        },
        imageStyles: {
          width: 64,
          height: 64
        },
        exportExcel: {
          "filename": "food-merchant-list.xls",
          "type": "xls",
          "fields": {
            "店铺名称": "store_name",
            "店铺图标": "store_icon",
            "店铺牌匾": "store_plaque_icon",
            "店铺电话": "store_phone",
            "营业日期": "store_work_date",
            "营业时段": "store_work_time",
            "配送时段": "store_delivery_time",
            "出餐时间": "store_food_finish_time",
            "餐具费用": "store_food_pack_fee",
            "基础配送费": "store_food_delivery_fee",
            "起送金额": "store_start_delivery_money",
            "店铺地址": "store_address_info",
            "店铺公告": "store_notice"
          }
        },
        exportExcelData: []
      }
    },
    onLoad() {
      this._filter = {}
      this.getHomeMenus();
    },
    mounted() {
      this.$refs.udb.loadData()
    },
    methods: {
      layerMerchantWallet(merchant){
        layerMerchantWallet.call(this,merchant)
      },
      async getHomeMenus(){
        const {result:{errCode,data}}= await db.collection(`food-home-menus`).field(`menu_name`).get()
        if(errCode===0){
          const renderList=data.map(it=>{
            return { text:it.menu_name, value:it._id}
          })
          this.options.store_category_menuId_valuetotext=renderList;
        }
        
      },

      previewImage(idStr,value){
        const canvas=document.createElement(`canvas`);
        canvas.height=200;
        canvas.width=200;
        const qr = new UQRCode();
        qr.data = value;
        qr.make();
        qr.canvasContext = canvas.getContext(`2d`);
        qr.drawCanvas();
        const base64=canvas.toDataURL()
        canvas.remove();
          uni.previewImage({
              urls:[base64],
              fail:(err)=>{
              uni.showToast({
                  title: '二维码查看失败，请联系管理员',
                  icon:`none`,
                  duration: 2000
                });
              }
          });
      },
      createQrCode(idStr,value){
        this.$nextTick().then(res=>{
          var qr = new UQRCode();
          qr.data = value;
          qr.size = this.imageStyles.width;
          qr.make();
          var canvasContext = uni.createCanvasContext(idStr, this); 
          qr.canvasContext = canvasContext;
          qr.drawCanvas();
        })
        return ''
      },
      onqueryload(data) {
        this.exportExcelData = data
      },
      getWhere() {
        const query = this.query.trim()
        if (!query) {
          return ''
        }
        const queryRe = new RegExp(query, 'i')
        return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
      },
      search() {
        const newWhere = this.getWhere()
        this.where = newWhere
        this.$nextTick(() => {
          this.loadData()
        })
      },
      loadData(clear = true) {
        this.$refs.udb.loadData({
          clear
        })
      },
      onPageChanged(e) {
        this.selectedIndexs.length = 0
        this.$refs.table.clearSelection()
        this.$refs.udb.loadData({
          current: e.current
        })
      },
      navigateTo(url, clear) {
        // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
        uni.navigateTo({
          url,
          events: {
            refreshData: () => {
              this.loadData(clear)
            }
          }
        })
      },
      // 多选处理
      selectedItems() {
        var dataList = this.$refs.udb.dataList
        return this.selectedIndexs.map(i => dataList[i]._id)
      },
      // 批量删除
      delTable() {
        this.$refs.udb.remove(this.selectedItems(), {
          action:`no-comfig-remove`,
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      // 多选
      selectionChange(e) {
        this.selectedIndexs = e.detail.index
      },
      confirmDelete(id) {
        this.$refs.udb.remove(id, {
          action:`no-comfig-remove`,
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      sortChange(e, name) {
        this.orderByFieldName = name;
        if (e.order) {
          this.orderby = name + ' ' + orderByMapping[e.order]
        } else {
          this.orderby = ''
        }
        this.$refs.table.clearSelection()
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      filterChange(e, name) {
        this._filter[name] = {
          type: e.filterType,
          value: e.filter
        }
        let newWhere = filterToWhere(this._filter, db.command)
        if (Object.keys(newWhere).length) {
          this.where = newWhere
        } else {
          this.where = ''
        }
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      }
    }
  }
</script>
